package com.yitiao.consumer;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class DynamicTopicConsumer {

    private final AmqpAdmin amqpAdmin;

    private final RabbitTemplate rabbitTemplate;

    public void consume(String exchangeName, String routingKey, String queueName,MessageListener messageListener){
        Exchange exchange = ExchangeBuilder.topicExchange(exchangeName).durable(true).build();
        amqpAdmin.declareExchange(exchange);

        Queue queue = new Queue(queueName, true, false, false);
        amqpAdmin.declareQueue(queue);

        Binding binding = BindingBuilder.bind(queue).to(exchange).with(routingKey).noargs();
        amqpAdmin.declareBinding(binding);

        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(rabbitTemplate.getConnectionFactory());
        container.setQueues(queue);
        container.setMessageListener(messageListener);
        container.start();
    }

    public void consume(String exchangeName, String routingKey,String queueName) {
        consume(exchangeName,routingKey,queueName,new DefaultMessageListener());
    }

}
